#include "userinfodialog.h"
#include "logindialog.h"
#include <QApplication>
#include <QMessageBox>
#include <QJsonParseError>
#include <QNetworkRequest>
#include <QDateTime>
#include <QDebug>
#include <QCryptographicHash>
#include <QByteArray>
#include <QGroupBox>
#include <QPainter>
#include <QPixmap>
#include "protection.h"

UserInfoDialog::UserInfoDialog(QWidget *parent)
    : QDialog(parent)
    , m_reply(nullptr)
    , m_apiManager(ApiManager::instance())
{
    setWindowTitle(tr("用户信息"));
    setModal(true);
    setFixedSize(400, 280);

    // 初始化ConfigManager
    ConfigManager::initialize();

    setupUI();
    setupStyles();
    setupConnections();
    loadUserInfo();
}

UserInfoDialog::~UserInfoDialog()
{
    if (m_reply) {
        m_reply->deleteLater();
    }
}

void UserInfoDialog::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setSpacing(10);
    m_mainLayout->setContentsMargins(30, 25, 30, 25);

    // 账户邮箱 - 同一行显示
    QHBoxLayout* emailLayout = new QHBoxLayout();
    m_emailLabel = new QLabel(tr("账户邮箱:"), this);
    m_emailLabel->setObjectName("infoLabel");
    m_emailValue = new QLabel(this);
    m_emailValue->setObjectName("valueLabel");
    emailLayout->addWidget(m_emailLabel);
    emailLayout->addWidget(m_emailValue, 1);
    m_mainLayout->addLayout(emailLayout);

    // 账户类型 - 同一行显示
    QHBoxLayout* typeLayout = new QHBoxLayout();
    m_typeLabel = new QLabel(tr("账户类型:"), this);
    m_typeLabel->setObjectName("infoLabel");
    m_typeValue = new QLabel(this);
    m_typeValue->setObjectName("valueLabel");
    typeLayout->addWidget(m_typeLabel);
    typeLayout->addWidget(m_typeValue, 1);
    m_mainLayout->addLayout(typeLayout);

    // 订阅状态 - 同一行显示，只有标签和水晶小圆图标
    QHBoxLayout* statusLayout = new QHBoxLayout();
    m_statusDisplayLabel = new QLabel(tr("订阅状态:"), this);
    m_statusDisplayLabel->setObjectName("infoLabel");
    m_statusIcon = new QLabel(this);
    m_statusIcon->setFixedSize(10, 10);
    statusLayout->addWidget(m_statusDisplayLabel);
    statusLayout->addWidget(m_statusIcon);
    statusLayout->addStretch(); // 添加弹性空间来对齐
    m_mainLayout->addLayout(statusLayout);

    // 订阅到期 - 同一行显示
    QHBoxLayout* expiryLayout = new QHBoxLayout();
    m_expiryLabel = new QLabel(tr("订阅到期:"), this);
    m_expiryLabel->setObjectName("infoLabel");
    m_expiryValue = new QLabel(this);
    m_expiryValue->setObjectName("valueLabel");
    expiryLayout->addWidget(m_expiryLabel);
    expiryLayout->addWidget(m_expiryValue, 1);
    m_mainLayout->addLayout(expiryLayout);

    // 设备名称 - 同一行显示
    QHBoxLayout* deviceLayout = new QHBoxLayout();
    m_deviceNameLabel = new QLabel(tr("设备名称:"), this);
    m_deviceNameLabel->setObjectName("infoLabel");
    m_deviceNameValue = new QLabel(this);
    m_deviceNameValue->setObjectName("valueLabel");
    deviceLayout->addWidget(m_deviceNameLabel);
    deviceLayout->addWidget(m_deviceNameValue, 1);
    m_mainLayout->addLayout(deviceLayout);

    m_mainLayout->addStretch();

    // 状态标签
    m_statusLabel = new QLabel(this);
    m_statusLabel->setObjectName("statusLabel");
    m_statusLabel->setWordWrap(true);
    m_statusLabel->setAlignment(Qt::AlignCenter);
    m_statusLabel->setFixedHeight(40);
    m_statusLabel->setVisible(false);
    m_mainLayout->addWidget(m_statusLabel);

    // 按钮区域
    m_buttonLayout = new QHBoxLayout();
    m_buttonLayout->setSpacing(12);

    // 退出登录按钮
    m_logoutButton = new QPushButton(tr("退出登录"), this);
    m_logoutButton->setObjectName("logoutButton");
    m_logoutButton->setFixedHeight(36);
    m_logoutButton->setMinimumWidth(120);

    // 关闭按钮
    m_closeButton = new QPushButton(tr("关闭"), this);
    m_closeButton->setObjectName("closeButton");
    m_closeButton->setFixedHeight(36);
    m_closeButton->setMinimumWidth(80);

    m_buttonLayout->addStretch();
    m_buttonLayout->addWidget(m_logoutButton);
    m_buttonLayout->addWidget(m_closeButton);
    m_mainLayout->addLayout(m_buttonLayout);

    m_mainLayout->addSpacing(10);
}

void UserInfoDialog::createInfoItem(const QString& labelText, QLabel*& label, QLabel*& value)
{
    // 创建标签 - 简洁样式
    label = new QLabel(labelText, this);
    label->setObjectName("infoLabel");
    m_mainLayout->addWidget(label);

    // 创建值框 - 与登录对话框保持一致的输入框样式
    value = new QLabel("--", this);
    value->setObjectName("valueLabel");
    value->setFixedHeight(40);  // 稍微减小高度，更紧凑
    m_mainLayout->addWidget(value);

    // 添加小间距
    m_mainLayout->addSpacing(6);
}

void UserInfoDialog::setupStyles()
{
    setStyleSheet(R"(
        QDialog {
            background-color: #F5F5F5;
        }

        QLineEdit {
            padding: 12px 16px;
            border: 1px solid #D5DBDB;
            border-radius: 6px;
            font-size: 13pt;
            background-color: white;
            color: #2C3E50;
        }

        QLineEdit:focus {
            border-color: #85929E;
            outline: none;
            background-color: #FAFAFA;
        }

        QLineEdit::placeholder {
            color: #AAB7B8;
        }

        #logoutButton, #closeButton {
            background-color: #f0f0f0;
            color: #333;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 11pt;
        }

        #logoutButton:hover, #closeButton:hover {
            background-color: #e0e0e0;
            border-color: #999;
        }

        #logoutButton:pressed, #closeButton:pressed {
            background-color: #d0d0d0;
        }

        #logoutButton:disabled, #closeButton:disabled {
            background-color: #F7F9FA;
            color: #BDC3C7;
            border-color: #E5E8E8;
        }

        #infoLabel {
            font-size: 12pt;
            color: #5D6D7E;
            font-weight: normal;
            margin-bottom: 2px;
        }

        #valueLabel {
            font-size: 12pt;
            font-weight: normal;
            color: #2C3E50;
            background-color: white;
            padding: 6px 10px;
            border: 1px solid #D5DBDB;
            border-radius: 4px;
        }

        #statusValue {
            font-size: 12pt;
            font-weight: normal;
            color: #2C3E50;
            background-color: white;
            padding: 6px 10px;
            border: 1px solid #D5DBDB;
            border-radius: 4px;
        }

        #statusLabel {
            font-size: 12pt;
            padding: 8px;
            border-radius: 4px;
            margin: 6px 0;
        }

        #statusLabel[type="error"] {
            background-color: #FADBD8;
            color: #C0392B;
            border: 1px solid #F1948A;
        }

        #statusLabel[type="success"] {
            background-color: #E8F8F5;
            color: #148F77;
            border: 1px solid #7DCEA0;
        }

        #statusLabel[type="loading"] {
            background-color: #EBF5FB;
            color: #2E86AB;
            border: 1px solid #AED6F1;
        }

        #statusLabel[type="info"] {
            background-color: #EBF5FB;
            color: #2E86AB;
            border: 1px solid #AED6F1;
        }
    )");
}

void UserInfoDialog::setupConnections()
{
    connect(m_logoutButton, &QPushButton::clicked, this, &UserInfoDialog::onLogoutClicked);
    connect(m_closeButton, &QPushButton::clicked, this, &UserInfoDialog::onCloseClicked);

    // 连接ApiManager信号
    if (m_apiManager) {
        connect(m_apiManager, &ApiManager::userProfileFetched, this, &UserInfoDialog::onUserProfileFetched);
        // 注意：订阅信息包含在用户信息响应中，不需要单独的订阅信号
        connect(m_apiManager, &ApiManager::apiError, this, &UserInfoDialog::onApiError);
        connect(m_apiManager, &ApiManager::logoutFinished, this, &UserInfoDialog::onLogoutFinished);
    }
}

void UserInfoDialog::loadUserInfo()
{

    // 从ConfigManager读取保存的用户信息
    QString userEmail = ConfigManager::getUserEmail();
    QString authToken = ConfigManager::getAuthToken(); // 使用新的authToken
    QString deviceName = ConfigManager::getDeviceName();

    // 读取email字段
    if (!userEmail.isEmpty()) {
        m_userEmail = userEmail;
        m_emailValue->setText(userEmail);
    }

    // 读取authToken字段并设置到ApiManager
    QJsonObject localSubscription = ConfigManager::getSubscriptionInfo();
    bool hasLocalSubscription = !localSubscription.isEmpty();

    if (!authToken.isEmpty()) {
        m_token = authToken; // 保持向后兼容
        m_apiManager->setAuthToken(authToken);

        // 优先从本地读取订阅信息
        if (hasLocalSubscription) {
            updateSubscriptionInfo(localSubscription);
        }

        // 使用新的API获取用户信息（用于更新数据）
        if (m_apiManager->hasValidToken()) {
            m_apiManager->fetchUserProfile();
            // 注意：订阅信息包含在用户信息响应中，不需要单独获取
        }

        // 同时解析本地token作为备用（仅在没有本地订阅信息时使用）
        QJsonObject payload = decodeJWTPayload(authToken);
        if (!payload.isEmpty()) {
            // 解析登录时间 (iat - issued at) - 仅记录，不显示
            if (payload.contains("iat")) {
                qint64 iat = payload["iat"].toVariant().toLongLong();
                QDateTime loginTime = QDateTime::fromSecsSinceEpoch(iat);
                m_loginTime = loginTime.toString("yyyy-MM-dd hh:mm:ss");
            }

            // 解析过期时间 (exp - expiry) - 仅在没有本地订阅信息时使用
            if (!hasLocalSubscription && payload.contains("exp")) {
                qint64 exp = payload["exp"].toVariant().toLongLong();
                QDateTime expiryTime = QDateTime::fromSecsSinceEpoch(exp);
                QString expiryStr = expiryTime.toString("yyyy-MM-dd hh:mm:ss");

                // 检查是否快要过期
                QDateTime now = QDateTime::currentDateTime();
                qint64 remainingDays = now.daysTo(expiryTime);

                if (remainingDays <= 0) {
                    m_expiryValue->setText(tr("已过期 (%1)").arg(expiryStr));
                    m_expiryValue->setStyleSheet("#valueLabel { background-color: #FADBD8; color: #C0392B; border-color: #F1948A; }");
                } else if (remainingDays <= 7) {
                    m_expiryValue->setText(tr("即将过期 (%1)").arg(expiryStr));
                    m_expiryValue->setStyleSheet("#valueLabel { background-color: #FEF9E7; color: #D68910; border-color: #F4D03F; }");
                } else {
                    m_expiryValue->setText(expiryStr);
                }

            }
        }
    }

    if (!deviceName.isEmpty()) {
        m_deviceName = deviceName;
        m_deviceNameValue->setText(deviceName);
    }

    // 设备ID已移除

    // 设置账户类型（仅在没有本地订阅信息时设置默认值）
    if (!hasLocalSubscription) {
        if (LoginDialog::isTrialUser()) {
            m_userType = tr("免费版");
            m_typeValue->setText(tr("免费版"));
            m_expiryValue->setText(tr("无限制"));
            updateSubscriptionStatus(false);
        } else {
            m_userType = tr("付费版");
            m_typeValue->setText(tr("付费版"));
            updateSubscriptionStatus(true);
        }
    }

}


QJsonObject UserInfoDialog::decodeJWTPayload(const QString& token)
{
    QStringList parts = token.split('.');
    if (parts.size() != 3) {
        return QJsonObject();
    }

    // JWT的payload是base64编码的第二部分
    QString payload = parts[1];

    // JWT base64编码可能缺少填充，需要补齐
    while (payload.length() % 4) {
        payload += '=';
    }

    QByteArray payloadData = QByteArray::fromBase64(payload.toUtf8());

    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(payloadData, &error);

    if (error.error != QJsonParseError::NoError) {
        return QJsonObject();
    }

    return doc.object();
}

void UserInfoDialog::onLogoutClicked()
{

    // 禁用按钮，防止重复点击
    m_logoutButton->setEnabled(false);
    m_logoutButton->setText(tr("注销中..."));

    // 调用服务器注销API
    performServerLogout();
}

void UserInfoDialog::onCloseClicked()
{
    accept();
}

void UserInfoDialog::setLoadingState(bool loading)
{
    m_logoutButton->setEnabled(!loading);
    m_closeButton->setEnabled(!loading);

    if (loading) {
        m_logoutButton->setText(tr("注销中..."));
    } else {
        m_logoutButton->setText(tr("退出登录"));
    }
}

void UserInfoDialog::performServerLogout()
{
    // 使用新的authToken系统
    QString authToken = ConfigManager::getAuthToken();
    if (authToken.isEmpty()) {
        clearLocalAuthAndExit();
        return;
    }


    // 使用新的ApiManager进行注销
    if (m_apiManager && m_apiManager->hasValidToken()) {
        m_apiManager->logout();

        // 设置超时（5秒），如果服务器响应慢则执行本地清理
        QTimer::singleShot(5000, this, [this]() {
            if (m_logoutButton->text() == tr("注销中...")) {
                clearLocalAuthAndExit();
            }
        });
    } else {
        clearLocalAuthAndExit();
    }
}


void UserInfoDialog::clearLocalAuthAndExit()
{
    // 防止重复调用
    if (m_isLoggingOut) {
        return;
    }

    m_isLoggingOut = true;

    // 停止心跳保活
    if (m_apiManager) {
        m_apiManager->stopHeartbeat();
    }

    // 清除所有认证信息
    ConfigManager::setUserToken("");        // 向后兼容
    ConfigManager::setAuthToken("");        // 新的authToken系统
    ConfigManager::clearSubscriptionInfo(); // 清除订阅信息
    ConfigManager::sync();

    // 设置为试用用户
    LoginDialog::updateUserStatus(true);


    // 发射退出登录信号
    emit logoutRequested();

    // 关闭对话框
    accept();
}

void UserInfoDialog::onUserProfileFetched(const QJsonObject& userProfile)
{

    // 更新邮箱信息（如果有更准确的信息）
    if (userProfile.contains("email")) {
        QString email = userProfile["email"].toString();
        if (!email.isEmpty()) {
            m_emailValue->setText(email);
            m_userEmail = email;
        }
    }

    // 更新其他用户信息
    if (userProfile.contains("name")) {
        QString name = userProfile["name"].toString();
    }

    if (userProfile.contains("id")) {
        QString userId = userProfile["id"].toString();
    }

    // 处理包含在用户信息中的订阅信息
    if (userProfile.contains("subscription") && userProfile["subscription"].isObject()) {
        QJsonObject subscription = userProfile["subscription"].toObject();

        // 保存订阅信息到本地
        ConfigManager::setSubscriptionInfo(subscription);

        // 更新UI显示
        updateSubscriptionInfo(subscription);
    }

}

void UserInfoDialog::updateSubscriptionInfo(const QJsonObject& subscription)
{

    // 如果订阅信息为空，清空显示
    if (subscription.isEmpty()) {
        m_typeValue->setText("");  // 清空账户类型
        m_expiryValue->setText(""); // 清空到期时间
        return;
    }

    // 更新订阅信息
    if (subscription.contains("type")) {
        QString type = subscription["type"].toString();
        bool active = subscription["active"].toBool();

        // 账户类型中文映射
        QString userTypeText;
        if (type == "free") {
            userTypeText = tr("免费版");
        } else if (type == "monthly") {
            userTypeText = tr("高级版-月付");
        } else if (type == "yearly") {
            userTypeText = tr("高级版-年付");
        } else if (type == "team") {
            userTypeText = tr("团队版");
        } else if (type == "enterprise") {
            userTypeText = tr("企业版");
        } else {
            userTypeText = type; // 使用原始类型名称
        }

        if (!active) {
            userTypeText += tr("（已过期）");
        }

        m_userType = userTypeText;
        m_typeValue->setText(userTypeText);

        // 更新订阅状态图标
        updateSubscriptionStatus(active);
    }

    // 检查到期时间相关字段
    QString expiryDateStr;
    if (subscription.contains("expiresAt")) {
        expiryDateStr = subscription["expiresAt"].toString();
    } else if (subscription.contains("endDate")) {
        expiryDateStr = subscription["endDate"].toString();
    } else if (subscription.contains("expiry")) {
        expiryDateStr = subscription["expiry"].toString();
    }

    if (!expiryDateStr.isEmpty()) {
        // 解析并格式化日期
        QDateTime expiryTime = QDateTime::fromString(expiryDateStr, Qt::ISODate);
        if (expiryTime.isValid()) {
            QString formattedDate = expiryTime.toString("yyyy-MM-dd");

            // 检查是否快要过期
            QDateTime now = QDateTime::currentDateTime();
            qint64 remainingDays = now.daysTo(expiryTime);

            if (remainingDays <= 0) {
                m_expiryValue->setText(tr("已过期 (%1)").arg(formattedDate));
                m_expiryValue->setStyleSheet("#valueLabel { background-color: #FADBD8; color: #C0392B; border-color: #F1948A; }");
            } else if (remainingDays <= 7) {
                m_expiryValue->setText(tr("即将过期 (%1)").arg(formattedDate));
                m_expiryValue->setStyleSheet("#valueLabel { background-color: #FEF9E7; color: #D68910; border-color: #F4D03F; }");
            } else {
                m_expiryValue->setText(formattedDate);
                m_expiryValue->setStyleSheet("#valueLabel { background-color: white; color: #2C3E50; border: 1px solid #D5DBDB; }");
            }

        } else {
            // 如果解析失败，直接显示原始字符串
            m_expiryValue->setText(expiryDateStr);
        }
    } else {
        m_expiryValue->setText(""); // 没有到期时间信息时清空显示
    }

}

void UserInfoDialog::onLogoutFinished(bool success)
{

    // 防止重复调用
    if (m_isLoggingOut) {
        return;
    }

    // 无论成功还是失败，都立即执行本地清理并关闭对话框
    clearLocalAuthAndExit();
}

void UserInfoDialog::onUserSubscriptionFetched(const QJsonObject& subscription)
{

    // 保存订阅信息到本地
    if (!subscription.isEmpty()) {
        ConfigManager::setSubscriptionInfo(subscription);
    }

    // 使用通用方法更新订阅信息
    updateSubscriptionInfo(subscription);

    // 更新订阅状态
    bool active = subscription["active"].toBool();
    updateSubscriptionStatus(active);

}
void UserInfoDialog::onApiError(const QString& error, const QString& details)
{

    // 如果用户信息获取失败，至少显示基本信息
    if (m_statusLabel) {
        m_statusLabel->setText(tr("无法获取详细信息: %1").arg(error));
        m_statusLabel->setStyleSheet("color: #E74C3C; font-size: 12px;");
    }
}

// 更新订阅状态显示
void UserInfoDialog::updateSubscriptionStatus(bool active)
{
    if (m_statusIcon) {
        QPixmap pixmap = createCrystalDot(active);
        m_statusIcon->setPixmap(pixmap);
    }
}

// 绘制水晶小圆图标
QPixmap UserInfoDialog::createCrystalDot(bool active) const
{
    QPixmap pixmap(10, 10);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);

    // 设置颜色 - 激活为绿色，非激活为灰色
    QColor crystalColor = active ? QColor(34, 197, 94) : QColor(142, 142, 147); // 绿色或灰色
    QColor highlightColor = active ? QColor(144, 238, 144) : QColor(189, 189, 189); // 浅绿色或浅灰色

    // 绘制外圆（水晶边框）
    painter.setPen(QPen(highlightColor.lighter(120), 1));
    painter.setBrush(QBrush(crystalColor));
    painter.drawEllipse(0, 0, 10, 10);

    // 绘制高光效果（水晶效果）
    painter.setPen(QPen(highlightColor.lighter(140), 1));
    painter.setBrush(Qt::NoBrush);
    painter.drawEllipse(2, 2, 6, 6);

    // 绘制内部高光点
    painter.setPen(QPen(highlightColor.lighter(160), 1));
    painter.drawEllipse(3, 3, 2, 2);

    return pixmap;
}

